jQuery.noConflict();
import {Constant} from './Constant.js';
(function($, PLUGIN_ID) {
  'use strict';
  $(function() {
    const message = {
      'en': {
        'msg_space_id': 'PivotTable Display Field Id',
        'msg_config_info_id': 'PivotTable ConfigInfo field Id',
        'msg_plugin_submit': '     Save   ',
        'msg_plugin_cancel': '     Cancel   ',
        'msg_appid_first_id': 'DataSource App1',
        'msg_appid_second_id': 'DataSource App2',
        'msg_required_field': 'Please enter the require fields!',
        'msg_same_appId_error': 'Please enter two different AppIDs!'
      },
      'zh': {
        'msg_space_id': '数据透视表显示字段ID',
        'msg_config_info_id': '数据透视表配置信息ID',
        'msg_plugin_submit': '     保存   ',
        'msg_plugin_cancel': '     返回   ',
        'msg_appid_first_id': '数据源1',
        'msg_appid_second_id': '数据源2',
        'msg_required_field': '请输入必填字段!',
        'msg_same_appId_error': '请输入两个不同的应用ID!'
      },
      'ja': {
        'msg_space_id': 'ピボット表示領域ID',
        'msg_config_info_id': 'ピボット構成情報ID',
        'msg_plugin_submit': '    保存する   ',
        'msg_plugin_cancel': '   キャンセル   ',
        'msg_appid_first_id': 'データソース1',
        'msg_appid_second_id': 'データソース2',
        'msg_required_field': '必須フィールドに入力してください！',
        'msg_same_appId_error': '2つの異なるAppIDを入力してください!'
      }
    };

    const lang = kintone.getLoginUser().language;
    const i18n = (lang in message) ? message[lang] : message['zh'];
    let spaceDropdown = {};
    let configDropdown = {};
    let firstAppIdDropdown = {};
    let secondAppIdDropdown = {};
    $('span[datatype="translate"]').each(function(i, elt) {
      $(elt).text(i18n[$(elt).attr('data-content')]);
    });
    const config = kintone.plugin.app.getConfig(PLUGIN_ID);
    const initData = ()=>{
      KintoneConfigHelper.getFields().then(function(resp) {
        const spaceItems = [];
        const configItems = [];
        const appIdItems = [];
        // eslint-disable-next-line consistent-return
        resp.forEach(elementInfo =>{
          if (elementInfo.hasOwnProperty('subtableCode')) {
            return false;
          }
          let item = {};
          switch (elementInfo.type) {
            case Constant.APP_DATA_TYPE_SPACER:
              item = {label: elementInfo.elementId,
                value: elementInfo.elementId,
                isDisabled: false};
              spaceItems.push(item);
              break;
            case Constant.APP_DATA_TYPE_MULTI_LINE_TEXT:
              item = {label: elementInfo.label ? elementInfo.label : elementInfo.code,
                value: elementInfo.code,
                isDisabled: false};
              configItems.push(item);
              break;
            case Constant.APP_DATA_TYPE_NUMBER:
              item = {label: elementInfo.label ? elementInfo.label : elementInfo.code,
                value: elementInfo.code,
                isDisabled: false};
              appIdItems.push(item);
              break;
          }
        });
        spaceDropdown = addSelectOption(spaceItems, Constant.CONFIG_SPACE_ID);
        configDropdown = addSelectOption(configItems, Constant.CONFIG_CONFIG_INFO_ID);
        firstAppIdDropdown = addSelectOption(appIdItems, Constant.CONFIG_FIRST_APP_ID);
        secondAppIdDropdown = addSelectOption(appIdItems, Constant.CONFIG_SECOND_APP_ID);
      }).catch(function(err) {
        alert(err);
      });

    };

    initData();
    const addSelectOption = (items, elementId)=>{
      const dropdown = new kintoneUIComponent
        .Dropdown({items: items, value: `${config[elementId] ? config[elementId] : ''}`});
      document.getElementById(`${elementId}`).appendChild(dropdown.render());
      return dropdown;
    };
    $('#plugin_submit').click(function() {
      const spaceId = spaceDropdown.getValue().trim();
      const configInfoId = configDropdown.getValue().trim();
      const firstAppId = firstAppIdDropdown.getValue().trim();
      const secondAppId = secondAppIdDropdown.getValue().trim();
      if (spaceId.length === 0 || configInfoId.length === 0 || firstAppId.length === 0 || secondAppId.length === 0) {
        alert(i18n.msg_required_field);
        return;
      }
      if (firstAppId !== undefined && firstAppId === secondAppId) {
        alert(i18n.msg_same_appId_error);
        return;
      }
      const submitConfig = {};
      submitConfig[`${Constant.CONFIG_SPACE_ID}`] = spaceId;
      submitConfig[`${Constant.CONFIG_CONFIG_INFO_ID}`] = configInfoId;
      submitConfig[`${Constant.CONFIG_SECOND_APP_ID}`] = secondAppId;
      submitConfig[`${Constant.CONFIG_FIRST_APP_ID}`] = firstAppId;
      kintone.plugin.app.setConfig(submitConfig);
    });

    $('#plugin_cancel').click(function() {
      history.back();
    });

  });
})(jQuery, kintone.$PLUGIN_ID);